import React, { useContext, useReducer } from "react";

const Context = React.createContext({});

function createRenderWidget(Component, initState, reducer, action) {
    const Widget = (props) => {
        const [state, dispatch] = useReducer(reducer, initState);
        var wrappedAction = {};
        for (let key in action) {
            wrappedAction[key] = action[key](state, dispatch);
        }
        return <Context.Provider value={{ state, wrappedAction }}>
            <Component />
        </Context.Provider>
    }
    return Widget;
}

const withState = (Component) => {
    const Consumer = (props) => {
        const context = useContext(Context);
        const { state, wrappedAction } = context;
        return (<Component
            {...props} state={state} {...wrappedAction} />);
    };
    return React.forwardRef((props, ref) => {
        return <Consumer {...props} forwardedRef={ref} />;
    });
};

export { Context, createRenderWidget, withState };
